<body>
<div>
    <label for="id">id: </label><input id="id"/>
    <label for="username">username: </label><input id="username"/>
    <label for="password">password: </label><input id="password">
</div>
<div>
    <button onclick="query()">Query</button>
    <button onclick="save()">Save</button>
    <button onclick="del()">Delete</button>
</div>

<div>
    <label for="pageNum"></label>pageNum (default: 1): <input id="pageNum"/>
    <label for="pageSize">pageSize (default 5): </label><input id="pageSize">
</div>
<button onclick="paginationQuery()">Pagination Query</button>
<pre id="data">

</pre>
<script>
    const idInput = document.getElementById('id')
    const usernameInput = document.getElementById('username')
    const passwordInput = document.getElementById('password')
    const pageNumInput = document.getElementById('pageNum')
    const pageSizeInput = document.getElementById('pageSize')
    const dataPre = document.getElementById('data')

    async function query() {
        let id = idInput.value
        let data
        if (id) {
            data = await (await fetch(`/get/${id}`)).json()
        } else {
            data = await (await fetch('/list')).json()
        }
        dataPre.innerHTML = JSON.stringify(data, null, 2)
    }

    async function save() {
        let id = idInput.value
        let username = usernameInput.value
        let password = passwordInput.value
        if (!username || !password) {
            alert('username and password must be filled')
            return
        }
        await fetch('/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({id, username, password})
        })
        idInput.value = ''
        await query()
    }

    async function del() {
        let id = idInput.value
        if (!id) {
            alert('id must be filled')
            return
        }
        await fetch(`/del/${id}`, {
            method: 'DELETE'
        })
        idInput.value = ''
        await query()
    }

    async function paginationQuery() {
        let pageNum = pageNumInput.value
        let pageSize = pageSizeInput.value
        if (!pageNum) {
            pageNum = 1
        }
        if (!pageSize) {
            pageSize = 5
        }
        let data = await (await fetch(
            `/page?pageNum=${encodeURIComponent(pageNum)}&pageSize=${encodeURIComponent(pageSize)}`
        )).json()
        dataPre.innerHTML = JSON.stringify(data, null, 2)
    }
</script>
</body>